package com.ltu.util.json;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.poi.ss.formula.functions.T;
/**
 * 
 * 1:将JavaBean转换成Map、JSONObject
 * 2:将Map转换成Javabean
 * 3:将JSONObject转换成Map、Javabean
 * 
 * @author Alexia
 */

public class JsonHelper {
    
	
    /**
     * 将Javabean转换为Map
     * 
     * @param javaBean
     *            javaBean
     * @return Map对象
     */
    public static Map<String, Object> toMap(Object javaBean) {

        Map<String, Object> result = new HashMap<>();
        Method[] methods = javaBean.getClass().getDeclaredMethods();

        for (Method method : methods) {

            try {

                if (method.getName().startsWith("get")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);

                    Object value = method.invoke(javaBean, (Object[]) null);
                    result.put(field, null == value ? "" : value.toString());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return result;

    }

    /**
     * 将Json对象转换成Map
     * 
     * @param jsonString
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
    @SuppressWarnings("rawtypes")
    public static Map<String, Object> getMap(String jsonString){
    	try {
			Map<String, Object> result = new HashMap<>();
			if(null != jsonString && jsonString.length() > 0){
				JSONObject jsonObject = new JSONObject(jsonString);
				Iterator iterator = jsonObject.keys();
				String key = null;
				String value = null;
				while (iterator.hasNext()) {
					key = (String) iterator.next();
					value = getStrObj(jsonObject.get(key));
					if(value.startsWith("{") && value.endsWith("}")){//TODO
						Map<String, Object> itemMap = getMap(value);
						result.put(key, itemMap);
					}else if(value.startsWith("[") && value.endsWith("]")){//TODO
						Vector<?> itemVec = getVec(value);
						result.put(key, itemVec);
					}else{
						result.put(key, value);
					}
				}
			}
			return result;
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	return new HashMap<>();
    }
    
    public static String getStrObj(Object obj){
    	if(obj instanceof String){
    		return (String) obj;
    	}else if(obj instanceof Number){
    		Number value = (Number) obj;
    		return value + "";
    	}else if(obj instanceof Boolean){
    		Boolean bool = (Boolean) obj;
    		return bool + "";
    	}
    	return "";
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Vector getVec(String vecStr){
    	try {
			Vector vec = new Vector();
			if(null != vecStr && vecStr.length() > 0){
				JSONArray array = new JSONArray(vecStr);
				for(int i = 0; i < array.length(); i ++){
					Object itemObj = array.get(i);
					String value = "";
					if(itemObj instanceof String){
						value = (String) array.get(i);
					}else if(itemObj instanceof JSONObject){
						JSONObject itemStrObj = (JSONObject) itemObj;
						value = itemStrObj.toString();
					}
					if(value.startsWith("{")){
						Map<String, Object> itemMap = getMap(value);
						vec.add(itemMap);
					}else if(value.startsWith("[")){
						Vector<Map<String, Object>> itemVec = getVec(value);
						vec.add(itemVec);
					}else{
						vec.add(value);
					}
				}
			}
			return vec;
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	return new Vector();
    }

    /**
     * 将JavaBean转换成JSONObject（通过Map中转）
     * 
     * @param bean
     *            javaBean
     * @return json对象
     */
    JSONObject toJSON(Object bean) {

        return new JSONObject(toMap(bean));

    }

    /**
     * 将Map转换成Javabean
     * 
     * @param javabean
     *            javaBean
     * @param data
     *            Map数据
     */
    public static Class<T> toJavaBean(Class<T> javabean, Map<String, Object> data) {

        Method[] methods = javabean.getClass().getDeclaredMethods();
        for (Method method : methods) {

            try {
                if (method.getName().startsWith("set")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("set") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    method.invoke(javabean, new Object[] {

                    data.get(field)

                    });

                }
            } catch (Exception e) {
            }

        }

        return javabean;

    }

    /**
     * JSONObject到JavaBean
     * 
     * @param
     *
     * @return json对象
     * @throws ParseException
     *             json解析异常
     * @throws JSONException
     */
    public static Class<T> toJavaBean(Class<T> javabean, JSONObject jsonObject)
            throws ParseException, JSONException {

        Map<String, Object> map = getMap(jsonObject.toString());

        return toJavaBean(javabean, map);

    }

}